package com.doyens.controller;

import com.doyens.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {


    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println("testString方法执行了.");
        User user = new User();
        user.setUsername("郭美美");
        user.setPassword("123123");
        user.setAge(50);
        model.addAttribute("user",user);

        return "success";
    }

    @RequestMapping("testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testvoid");
        //还想跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        return;
    }
    @RequestMapping("/testResponse")
    public void testResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testvoid");
        //还想跳转页面
    //    request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("你好");
        return;
    }

    @RequestMapping("/testAjax")
    @ResponseBody  //转json格式了
    public List<User>  findAll(){
        User user = new User();
        user.setUsername("张三");
        user.setAge(20);
        user.setPassword("123123");
        User user1 = new User();
        user1.setUsername("肖战");
        user1.setPassword("4567");
        user1.setAge(30);
        List<User>  list = new ArrayList<User>();
        list.add(user);
        list.add(user1);
        return list;
    }

    @PostMapping("/addUser")
    @ResponseBody
    public void  addUser(@RequestBody User user){
        System.out.println(user);
    }

}
